package com.sicnu.startup.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.sicnu.startup.service.OssService;
import com.sicnu.startup.util.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Resource
    private ConstantPropertiesUtil constantPropertiesUtil;

    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endpoint = constantPropertiesUtil.getEndPoint();
        String accessKeyId = constantPropertiesUtil.getAccessKeyId();
        String accessKeySecret = constantPropertiesUtil.getAccessKeySecret();
        String bucketName = constantPropertiesUtil.getBucketName();
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            // 获取文件名称
            String fileName = file.getOriginalFilename();
            //生成随机唯一值，使用uuid，添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;

            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //  2021/02/02/01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = timeUrl + "/" + fileName;

            //调用方法实现上传
            // 1.jpg    /a/b/1.jpg
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //上传之后文件路径
//            https://crowd0302.oss-cn-chengdu.aliyuncs.com/20211021/0692d2bb3df34d799239e0219f72925a.jpg
            // https://yygh-atguigu.oss-cn-beijing.aliyuncs.com/01.jpg
//            oss-cn-beijing.aliyuncs.com
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            //返回
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
